import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:todo_app/controllers/definitions/RtcRoomModel.dart';
import 'package:todo_app/hooks/LocalRtcVideoController.dart';
import 'package:todo_app/hooks/RTCPeerConnectionController.dart';
import 'package:todo_app/hooks/RemoteRtcVideoController.dart';
import 'package:todo_app/layout/Gaps.dart';
import 'package:todo_app/layout/Space.dart';
import 'package:todo_app/utils/call/CallHelper.dart';
import 'package:todo_app/utils/webrtc/section/CallIcons.dart';

class TalkSection extends HookWidget {
  const TalkSection(this.room, {Key? key}) : super(key: key);
  final RtcRoomModel room;

  @override
  Widget build(BuildContext context) {
    var localController = useLocalRtcVideoController();
    var remoteController = useRemoteRtcVideoController();
    var pcController = useRTCPeerConnectionController(room);

    useEffect(() {
      pcController.onTrack = (event) {
        remoteController.addTrack(event.streams[0], event.track);
      };
      pcController.onOfferReceived = (pc) async {
        if(room.user_id != room.created_by) {
          await localController.getUserMedia();
          localController.stream?.getTracks().forEach((track) {
            pc.addTrack(track, localController.stream!);
          });
          await pcController.createAnswer();
        }
      };
      localController.onInited = () async {
        var pc = await pcController.createPc();
        if(room.user_id == room.created_by) {
          await localController.getUserMedia();
          localController.stream?.getTracks().forEach((track) {
            pc.addTrack(track, localController.stream!);
          });
        }
        // pc 创建完成后 发送加入房间信号 避免传递offer没有意义
        pcController.sendJoinedRoomMsg();
      };
      return () {};
    }, []);

    Widget buildToolbar() {
      return Positioned(
        bottom: 70.dp,
        left: 0,
        right: 0,
        child: Space(
          mainAxisAlignment: MainAxisAlignment.center,
          gutter: 24.dp,
          children: [
            GestureDetector(
              onTap: () => localController.toggleCamera(), 
              child: ClipRRect(
                borderRadius: BorderRadius.circular(32.dp),
                child: Container(
                  width: 64.dp,
                  height: 64.dp,
                  color:  Colors.white,
                  child: const Icon(Icons.refresh, color: Colors.black),
                )
              ),
            ),
            GestureDetector(
              onTap: () {
                CallUIHelper.handUp(room.room_id!);
              },
              child: const CallEndIcon(),
            ),
            GestureDetector(
              onTap: () => remoteController.toggleSpeakerphone(),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(32.dp),
                child: Container(
                  width: 64.dp,
                  height: 64.dp,
                  color:  remoteController.speakerphoneOn ? Colors.white : Colors.white54,
                  child: Icon(Icons.speaker_phone, color: remoteController.speakerphoneOn ? Colors.black : Colors.white,),
                )
              ),
            )
          ]
        ),
      );
    }

    var localVideoView = RTCVideoView(
      localController.renderer,
      objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
      mirror: true
    );

    var remoteVideoView =  RTCVideoView( 
      remoteController.renderer,
      mirror: false
    );

    Widget buildFullVideo() {
      return Column(
        children: [
          Expanded(
            child: localController.isMini ? remoteVideoView : localVideoView
          ),
          Container(
            height: 200.dp,
            color: Colors.black,
          )
        ],
      );
    }

    Widget buildSmallVideo() {
      return Positioned(
        top: 100.dp,
        right: 22.dp,
        width: 120.dp,
        height: 160.dp,
        child: GestureDetector(
          onTap: () {
            localController.toggleMiniUi();
          },
          child: localController.isMini ? localVideoView : remoteVideoView
        )
      );
    }

    return Scaffold(
      body: Stack(
        children: [
          buildFullVideo(),
          buildSmallVideo(),
          buildToolbar()
        ],
      ),
    );
  }
}